<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div v-show="showSearch" class="mb-[10px]">
        <el-card shadow="hover" body-style="auto">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true" lable-width="auto">
            <el-form-item label="文件名" prop="documentName">
              <el-input v-model="queryParams.documentName" placeholder="请输入文件名" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="文件大小低于" prop="documentSize" label-width="100px">
              <el-input  v-model="inputdocumentSize" placeholder="请输入文件大小" clearable @keyup.enter="handleQuery"  style="width: 120px"/>
              <el-select v-model="selectDocumentSize" style="width: 80px" >
                <el-option
                  v-for="item in ['KB','MB','GB']"
                  :label="item"
                  :value="item">
                </el-option>
              </el-select>
            </el-form-item>

            <el-form-item label="备注" prop="remark">
              <el-input v-model="queryParams.remark" placeholder="请输入备注" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="Search" @click="handleQuery" round>搜索</el-button>
              <el-button icon="Refresh" @click="resetQuery" round>重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </div>
    </transition>

    <el-card shadow="never" style="height: 60px;">

      <template #header>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" plain icon="Upload" @click="handleImport" v-hasPermi="['commission:documentUpload:add']">上传</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="success" @click="selectAll" plain>全选</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="info" @click="deleteSelected" plain>取消选中</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" plain icon="Delete" @click="handleDelete()" v-hasPermi="['commission:documentUpload:remove']" v-if="$auth.hasRoleOr(['superadmin'])" >删除</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="primary" @click="handleExport" plain>下载</el-button>
          </el-col>
          <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>
      </template>
    </el-card>
      <el-card shadow="never" style="height: 550px;overflow: auto;">
        <div style=" height: 500px;text-align:center;display: grid;place-items: center; " v-if="checkEmpty()">
          <p style="font-size: large;color: #3a84de;font-weight: bold;">暂无文件</p>
        </div>
      <el-row v-for="(documentUpload, index) in documentUploadList" v-loading="loading" @selection-change="handleSelectionChange"  style="transition: box-shadow 0.3s ease;box-shadow: #4a5663; margin-bottom: 10px">
        <template #default="{ row }">
          <el-col :span="1">
          <el-checkbox v-model="ids[index]"></el-checkbox>
          </el-col>
          <el-col :span="19">
            <!-- 这里是每行的内容，假设有需要显示的数据 -->

            <div style="font-size: large;color: #3a84de;font-weight: bold; height: 30px" >{{documentUpload.documentName}}</div>
            <div style="height: 30px;display: inline-flex;align-items: center;width: 1200px;" >
              <p style="font-weight: lighter;font-size: medium;color: lightslategray;margin-right:5px;">备注:</p>
<!--              <el-tooltip v-if="documentUpload.remark" effect="dark" :content="documentUpload.remark" placement="top-start" style=" max-width: 20%;">-->
<!--                <p style="display: inline-block; width: 150px;white-space: nowrap; overflow: hidden; text-overflow: ellipsis;">{{documentUpload.remark?documentUpload.remark:'无'}}</p>-->
<!--              </el-tooltip>-->
              <p style="white-space: nowrap; overflow: hidden;width: 1000px;text-overflow: ellipsis;">{{documentUpload.remark?documentUpload.remark:'无'}}</p>
            </div>
            <div style="height: 50px; font-weight: lighter;font-size: medium;color: lightslategray;border-bottom: 1px dashed lightslategray ">
              <span style="margin-right:25px ">文件大小:{{formatBytes(documentUpload.documentSize) }}</span>
              <span style="margin-right:25px">上传时间:{{documentUpload.createTime}}</span>
              <span>下载次数:{{ documentUpload.downloads }}次</span>
            </div>
          </el-col>
          <el-col :span="4" class="text-right" >
            <el-tooltip content="查看" placement="top">
              <el-button type="text" icon="Document" @click="handleCheck(documentUpload)" style="font-size: 20px"></el-button>
            </el-tooltip>
            <el-tooltip content="下载" placement="top">
            <el-button type="text" icon="Download" @click="handleDownload(documentUpload)" style="font-size: 20px"></el-button>
            </el-tooltip>
            <el-tooltip content="编辑" placement="top">
              <el-button type="text" icon="Edit" @click="handleUpdate(documentUpload)" style="font-size: 20px" v-if="$auth.hasRoleOr(['superadmin'])"></el-button>
            </el-tooltip>
            <el-tooltip content="删除" placement="top">
            <el-button  type="text" icon="Delete" @click="handleDelete(documentUpload)" style="font-size: 20px" v-if="$auth.hasRoleOr(['superadmin'])"></el-button>
            </el-tooltip>
          </el-col>
        </template>
      </el-row>
    </el-card>
    <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" @pagination="getList"/>
    <!-- 添加或修改上传与下载附件对话框 -->
    <el-dialog :title="dialog.title" v-model="dialog.visible" width="500px" append-to-body>
      <el-form ref="documentUploadFormRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="文件名" prop="documentName">
          <el-input v-model="form.documentName" placeholder="请输入文件名" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
            <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

<!--    查看文件备注-->
    <el-dialog v-model="check.open" :title="check.title" width="400px" append-to-body >
      <div style="display: flex; justify-content: center; padding: 1em;">
        <p style="width: 300px;height: auto;text-indent: 2em;">{{check.content?check.content:'无'}}</p>
      </div>
    </el-dialog>

    <!-- 用户导入对话框 -->
    <el-dialog v-model="upload.open" :title="upload.title" width="400px" append-to-body>
      <el-form ref="ossFormRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="文件名">
          <fileUpload v-model="form.file" :file-type="[]" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancelUpload">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="DocumentUpload" lang="ts">
import {
  listDocumentUpload,
  getDocumentUpload,
  delDocumentUpload,
  addDocumentUpload,
  updateDocumentUpload,
  addDownloads
} from '@/api/commission/documentUpload';
import { DocumentUploadVO, DocumentUploadQuery, DocumentUploadForm } from '@/api/commission/documentUpload/types';
import {globalHeaders} from "@/utils/request";
import {blobValidate} from "@/utils/ruoyi";
import FileSaver from "file-saver";
import { LoadingInstance } from 'element-plus/es/components/loading/src/loading';
import axios from 'axios';

let downloadLoadingInstance: LoadingInstance;

const { proxy } = getCurrentInstance() as ComponentInternalInstance;

const documentUploadList = ref<DocumentUploadVO[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number | boolean>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);

//选择文件大小单位
const selectDocumentSize = ref('KB');
let inputdocumentSize = ref();
/*** 用户导入参数 */
const upload = reactive<ImportOption>({
  // 是否显示弹出层（用户导入）
  open: false,
  // 弹出层标题（用户导入）
  title: '',

  fileName: '',
  newDocumentName:'',
  remark: '',
  // 是否禁用上传
  isUploading: false,
  // 是否更新已经存在的用户数据
  // 设置上传的请求头部
  headers: globalHeaders(),
  // 上传的地址
  url: import.meta.env.VITE_APP_BASE_API + '/commission/documentUpload/importData'
});

const queryFormRef = ref<ElFormInstance>();
const documentUploadFormRef = ref<ElFormInstance>();
const uploadRef = ref<ElUploadInstance>();

const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

const check = reactive<DialogOption>({
  open:false,
  title:'',
  content:'',
});

const initFormData: DocumentUploadForm = {
  id: undefined,
  documentName: undefined,
  documentType: undefined,
  documentSize: undefined,
  downloads: undefined,
  remark: undefined,
  createTime:undefined,
}
const data = reactive<PageData<DocumentUploadForm, DocumentUploadQuery>>({
  form: {...initFormData},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    documentName: undefined,
    documentType: undefined,
    documentSize: undefined,
    remark: undefined,
    params: {
    }
  },
  rules: {
    id: [
      { required: true, message: "序号不能为空", trigger: "blur" }
    ],
    documentName: [
      { required: true, message: "文件名不能为空", trigger: "blur" }
    ],
    documentType: [
      { required: true, message: "文件格式不能为空", trigger: "change" }
    ],
    documentSize: [
      { required: true, message: "文件大小不能为空", trigger: "blur" }
    ],
    downloads: [
      { required: true, message: "下载人数不能为空", trigger: "blur" }
    ],
    remark: [
      { required: true, message: "备注不能为空", trigger: "blur" }
    ],
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询上传与下载附件列表 */
const getList = async () => {
  loading.value = true;
  const res = await listDocumentUpload(queryParams.value);
  documentUploadList.value = res.rows;
  total.value = res.total;
  loading.value = false;
}

/** 取消按钮 */
const cancel = () => {
  reset();
  dialog.visible = false;
}

/** 取消文件上传按钮 */
const cancelUpload = () => {
  form.value.file = undefined;
  upload.open = false;
}

/** 表单重置 */
const reset = () => {
  form.value = {...initFormData};
  documentUploadFormRef.value?.resetFields();
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  if(inputdocumentSize.value == null || inputdocumentSize.value == '')
  {
    queryParams.value.documentSize = null;
  }else if (selectDocumentSize.value=='KB') {
    queryParams.value.documentSize = Math.ceil(inputdocumentSize.value * 1024);
  }
  else if(selectDocumentSize.value == 'MB')
  {
    queryParams.value.documentSize = Math.ceil(inputdocumentSize.value * 1024 * 1024);

  }else if(selectDocumentSize.value == 'GB')
  {
    queryParams.value.documentSize = Math.ceil(inputdocumentSize.value * 1024 * 1024 * 1024);
  }
  getList();
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  queryParams.value.documentSize = undefined;
  inputdocumentSize.value = null;
  selectDocumentSize.value = 'KB';
  handleQuery();
}

/** 多选框选中数据 */
const handleSelectionChange = (selection: DocumentUploadVO[]) => {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
const handleUpload = () => {
  reset();
  dialog.visible = true;
  dialog.title = "添加上传与下载附件";
}

/** 下载按钮操作 */
const handleDownload = async (row) => {
  downloadLoadingInstance = ElLoading.service({ text: '正在下载数据，请稍候', background: 'rgba(0, 0, 0, 0.7)' });
  try {
    const res = await axios({
      method: 'get',
      url: row.url,
      responseType: 'blob',
      headers: globalHeaders()
    });
    const isBlob = blobValidate(res.data);
    if (isBlob) {
      const blob = new Blob([res.data], { type: 'application/octet-stream' });
      FileSaver.saveAs(blob, decodeURIComponent(row.documentName as string));
      //下载成功,发起添加下载数的请求
      await addDownloads(row.id);
      getList();//刷新列表
    } else {
      this.printErrMsg(res.data);
    }
    downloadLoadingInstance.close();
  } catch (r) {
    console.error(r);
    ElMessage.error('下载文件出现错误，请联系管理员！');
    downloadLoadingInstance.close();
  }
};

/** 修改按钮操作 */
const handleUpdate = async (row?: DocumentUploadVO) => {
  reset();
  const _id = row?.id || ids.value[0];
  const res = await getDocumentUpload(_id);
  Object.assign(form.value, res.data);
  dialog.visible = true;
  dialog.title = "修改上传与下载附件";
}


/** 查看按钮操作 */
const handleCheck = (row) => {
  check.open = true;
  check.title = "查看备注";
  check.content = row.remark;
}

/** 提交按钮 */
const submitForm = () => {
  if(form.value.file){
    addDocumentUpload(form.value.file).finally(() => {
      upload.open = false;
      form.value.file = undefined;
    });
    proxy?.$modal.msgSuccess("操作成功");
    getList();
  }
  else{
    documentUploadFormRef.value?.validate(async (valid: boolean) => {
      if (valid) {
        buttonLoading.value = true;
        if (form.value.id) {
          await updateDocumentUpload(form.value).finally(() =>  buttonLoading.value = false);
        } else {
          await addDocumentUpload(form.value).finally(() => upload.open = false);
        }
        proxy?.$modal.msgSuccess("操作成功");
        dialog.visible = false;
        await getList();
      }
    });
  }
}

/** 删除按钮操作 */
const handleDelete = async (row?: DocumentUploadVO) => {
  let _ids = row?.id || [];
  if(!row?.id){
    let delIds=[];
    for(var i=0;i<documentUploadList.value.length;i++){
      if(ids.value[i]==true){
        delIds[delIds.length] = documentUploadList.value[i].id;
      }
    }
    // const _ids = row?.id || ids.value;
    _ids =  delIds;
    // 设置所有元素为 false
    ids.value.forEach((item, index) => {
      ids.value[index] = false;
    });

  }

  await proxy?.$modal.confirm('是否确认删除上传与下载附件编号为"' + _ids + '"的数据项？').finally(() => loading.value = false);
  await delDocumentUpload(_ids);
  proxy?.$modal.msgSuccess("删除成功");
  await getList();
}

// 全选
const selectAll=() => {
    documentUploadList.value.forEach((item, index) => {
      ids.value[index] = true;
    });
};

// 取消选中
const deleteSelected= async (row?: DocumentUploadVO) => {
  documentUploadList.value.forEach((item, index) => {
    ids.value[index] = false;
  });
};

/** 导出按钮操作 */
const handleExport = () => {
  for(var i=0;i<documentUploadList.value.length;i++)
  {
    if(ids.value[i] == true){
      handleDownload(documentUploadList.value[i]);
    }
  }
};

/** 附件上传按钮操作 */
const handleImport = () => {
  upload.title = '附件上传';
  upload.open = true;
};

const formatBytes=(bytes)=> {
  if (bytes === 0) return '0 Bytes';
  const k = 1024;
  const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
  const i = Math.floor(Math.log(bytes) / Math.log(k));
  return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
};

/** 检查文件列表是否为空 */
function checkEmpty() {
  if(documentUploadList.value.length <= 0){
    return true;
  }
  return false;
}

/** 提交上传文件 */
function submitFileForm() {
  uploadRef.value?.submit();
}

onMounted(() => {
  getList();
});
</script>
